package com.food.restaurantpro.activity;

import com.food.restaurantpro.R;
import com.food.restaurantpro.RestaurantApp;
import com.food.restaurantpro.fragments.AboutUsFragment;
import com.food.restaurantpro.fragments.EditReservationFragment;
import com.food.restaurantpro.fragments.FoodGridViewFragment;
import com.food.restaurantpro.fragments.LoginFragment;
import com.food.restaurantpro.fragments.MenuGridViewFragment;
import com.food.restaurantpro.fragments.MenuPreOrderFragment;
import com.food.restaurantpro.fragments.PlacesFragment;
import com.food.restaurantpro.fragments.PromotionDetailFragment;
import com.food.restaurantpro.fragments.PromotionListViewFragment;
import com.food.restaurantpro.fragments.ReservationAddMoreInfoFragment;
import com.food.restaurantpro.fragments.ReservationFragment;
import com.food.restaurantpro.fragments.SaleFragment;
import com.food.restaurantpro.fragments.YourPreOrderFragment;
import com.food.restaurantpro.managingnetwork.ManagingNetwork;
import com.food.restaurantpro.objects.Promotion;
import com.food.restaurantpro.objects.Reservation;
import com.food.restaurantpro.utils.Utils;

import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.app.ProgressDialog;
import android.content.res.Configuration;

public class MainActivity extends ActionBarActivity implements OnClickListener {
	public static final String STRNAME_MYSHARED = "current_menu";

	private DrawerLayout mDrawerLayout;
	private ActionBarDrawerToggle mDrawerToggle;
	private Button mBtnMembership;
	private Button mBtnPromotion;
	public Button mBtnMenu;
	private Button mBtnPreOder;
	private Button mBtnReservation;
	private Button mBtnPlaces;
	private Button mBtnAboutUs;
	private Button mBtnSettings;
	private RelativeLayout menuLeftDrawer;
	private ProgressDialog _waitingDialog;
	
	LoginFragment loginFragment;
	AboutUsFragment aboutUsFragment;
	ReservationFragment reservationFragment;
	EditReservationFragment editReservationFragment;
	ReservationAddMoreInfoFragment reservationAddMoreInfoFragment;
	SaleFragment saleFragment;
	MenuGridViewFragment menuGridViewFragment;
	PromotionListViewFragment promotionListViewFragment;
	PlacesFragment placesFragment;
	
	public void showProcessDialog() {
		if (_waitingDialog == null || !_waitingDialog.isShowing()) {
			_waitingDialog = new ProgressDialog(this);
			_waitingDialog.setMessage(getString(R.string.processing));
			_waitingDialog.setCancelable(false);
			_waitingDialog.show();
		}
	}
	
	public void showProcessDialog(String message) {
		if (_waitingDialog == null || !_waitingDialog.isShowing()) {
			_waitingDialog = new ProgressDialog(this);
			_waitingDialog.setMessage(message);
			_waitingDialog.setCancelable(false);
			_waitingDialog.show();
		}
	}

	//Ham nay phai duoc goi trong onDestroy
	//Vi co truong hop dang request thi destroy activity
	//dialog se ko duoc dong neu ko dat ham nay trong onDestroy
	public void hideProcessDialog() {
		if (_waitingDialog != null && _waitingDialog.isShowing()) {
			_waitingDialog.dismiss();
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//Dang ky de quan ly network, trong onDestroy phai goi unRegisterReceiver
		ManagingNetwork.registerReceiver(RestaurantApp.CURRENT_CONTEXT);
		//layout cua ca man hinh main, bao gom ca menu
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		//he thong menu ben trai. cai nay chi su dung 1 cho duy nhat la close menu
		menuLeftDrawer = (RelativeLayout) findViewById(R.id.left_drawer);
		
		//Load control from resource
		mBtnMembership = (Button) findViewById(R.id.btnMembershipMain);
		mBtnPromotion = (Button) findViewById(R.id.btnPromotionMain);
		mBtnMenu = (Button) findViewById(R.id.btnMenuMain);
		mBtnPreOder = (Button) findViewById(R.id.btnPreOderMain);
		mBtnReservation = (Button) findViewById(R.id.btnReservationMain);
		mBtnPlaces = (Button) findViewById(R.id.btnPlacesMain);
		mBtnAboutUs = (Button) findViewById(R.id.btnAboutUsMain);
		mBtnSettings = (Button) findViewById(R.id.btnSettingMain);
		
		mBtnMembership.setOnClickListener(this);
		mBtnMenu.setOnClickListener(this);
		mBtnReservation.setOnClickListener(this);
		mBtnPromotion.setOnClickListener(this);
		mBtnPreOder.setOnClickListener(this);
		mBtnAboutUs.setOnClickListener(this);
		mBtnPlaces.setOnClickListener(this);
		
		/** Start config ActionBarDrawer */
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(false);
			getActionBar().setHomeButtonEnabled(true);
			getActionBar().setIcon(null);
			getActionBar().setDisplayUseLogoEnabled(true);
			getActionBar().setLogo(R.drawable.icon_menu);
			getActionBar().setDisplayShowTitleEnabled(false);
//			getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#dc101e")));
			getActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.red_bg));
			getActionBar().setDisplayShowCustomEnabled(true);
			getActionBar().setCustomView(R.layout.textview_headermain);			
		} else {
			getSupportActionBar().setDisplayHomeAsUpEnabled(false);
			getSupportActionBar().setHomeButtonEnabled(true);
			getSupportActionBar().setIcon(null);
			getSupportActionBar().setDisplayUseLogoEnabled(true);
			getSupportActionBar().setLogo(R.drawable.icon_menu);
			getSupportActionBar().setDisplayShowTitleEnabled(false);
//			getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#dc101e")));
			getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.red_bg));
			getSupportActionBar().setDisplayShowCustomEnabled(true);
			getSupportActionBar().setCustomView(R.layout.textview_headermain);
		}
		
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.icon_menu, R.string.title_restaurent_name, R.string.title_restaurent_name) {
			public void onDrawerClosed(View view) {
				/*Cho android api 11 tro len
				invalidateOptionsMenu();*/
				//android 2.3 tro len
				ActivityCompat.invalidateOptionsMenu(MainActivity.this);
			}
			public void onDrawerOpened(View drawerView) {
				/*Cho android api 11 tro len
				invalidateOptionsMenu();*/
				//android 2.3 tro len
				ActivityCompat.invalidateOptionsMenu(MainActivity.this);
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);
		
		/** End config ActionBarDrawer */
		
		//Create Fragments
		showSaleFragment();
	}
	
	
	/** Start config ActionBarDrawer */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}
	
	/** End Config ActionBarDrawer */
	
	
	//start fragments
	public void unSelectedAll(){
		mBtnReservation.setSelected(Boolean.FALSE);
		mBtnPreOder.setSelected(Boolean.FALSE);
		mBtnSettings.setSelected(Boolean.FALSE);
		mBtnPlaces.setSelected(Boolean.FALSE);
		mBtnMembership.setSelected(Boolean.FALSE);
		mBtnMenu.setSelected(Boolean.FALSE);
		mBtnMembership.setSelected(Boolean.FALSE);
		mBtnPromotion.setSelected(Boolean.FALSE);
		mBtnAboutUs.setSelected(Boolean.FALSE);
	}
	
	public void showSaleFragment(){
		finishAllFragment();
		saleFragment = new SaleFragment();
		//Xu ly UI
		unSelectedAll();
		mDrawerLayout.closeDrawer(menuLeftDrawer);
		 // update the main content by replacing fragments
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, saleFragment).commit();
	}

	public void showMembershipFragment(){
		if(!mBtnMembership.isSelected()) {
			finishAllFragment();
			loginFragment = new LoginFragment();
			//Xu ly UI
			unSelectedAll();
			mBtnMembership.setSelected(true);
			mDrawerLayout.closeDrawer(menuLeftDrawer);
			 // update the main content by replacing fragments
	        FragmentManager fragmentManager = getSupportFragmentManager();
	        fragmentManager.beginTransaction().replace(R.id.content_frame, loginFragment).commit();
		} else {
			mDrawerLayout.closeDrawer(menuLeftDrawer);
		}
	}
	
	public void showAboutUsFragment(){
		if(!mBtnAboutUs.isSelected()) {
			finishAllFragment();
			aboutUsFragment = new AboutUsFragment();
			//Xu ly UI
			unSelectedAll();
			mBtnAboutUs.setSelected(true);
			mDrawerLayout.closeDrawer(menuLeftDrawer);
			// update the main content by replacing fragments
			FragmentManager fragmentManager = getSupportFragmentManager();
			fragmentManager.beginTransaction().replace(R.id.content_frame, aboutUsFragment).commit();
		} else {
			mDrawerLayout.closeDrawer(menuLeftDrawer);
		}
	}
	
	public void showMenuFragment() {
		if(!mBtnMenu.isSelected()) {
			finishAllFragment();
			menuGridViewFragment = new MenuGridViewFragment();
			//Xu Ly UI
			unSelectedAll();
			mBtnMenu.setSelected(true);
			mDrawerLayout.closeDrawer(menuLeftDrawer);
			 // update the main content by replacing fragments
	        FragmentManager fragmentManager = getSupportFragmentManager();
	        fragmentManager.beginTransaction().replace(R.id.content_frame, menuGridViewFragment).commit();
		} else {
			mDrawerLayout.closeDrawer(menuLeftDrawer);
		}
	}
	
	public void showReservationFragment() {
		if(!mBtnReservation.isSelected()) {
			finishAllFragment();
			//Xu Ly UI
			unSelectedAll();
			mBtnReservation.setSelected(true);
			mDrawerLayout.closeDrawer(menuLeftDrawer);
			// update the main content by replacing fragments
			if(RestaurantApp.userInfo != null && !Utils.isEmpty(RestaurantApp.userInfo.getGenerateId())) {
				reservationFragment = new ReservationFragment();
				FragmentManager fragmentManager = getSupportFragmentManager();
				fragmentManager.beginTransaction().replace(R.id.content_frame, reservationFragment).commit();
			} else {
				reservationAddMoreInfoFragment = new ReservationAddMoreInfoFragment();
				FragmentManager fragmentManager = getSupportFragmentManager();
				fragmentManager.beginTransaction().replace(R.id.content_frame, reservationAddMoreInfoFragment).commit();
			}
		} else {
			mDrawerLayout.closeDrawer(menuLeftDrawer);
		}
	}
	
	public void showNextReservationFragment() {
		finishAllFragment();
		reservationFragment = new ReservationFragment();
		FragmentManager fragmentManager = getSupportFragmentManager();
		fragmentManager.beginTransaction().replace(R.id.content_frame, reservationFragment).commit();
	}
	
	public void showEditReservationFragment(Reservation reservation) {
		finishAllFragment();
		editReservationFragment = new EditReservationFragment();
		editReservationFragment.setReservation(reservation);
		FragmentManager fragmentManager = getSupportFragmentManager();
		fragmentManager.beginTransaction().replace(R.id.content_frame, editReservationFragment).commit();
	}
	
	/**
	 * This method is called when click on promotion
	 * @param promotion
	 */
	private PromotionDetailFragment promotionDetailFragment;
	public void showPromotionDetailFragment(Promotion promotion) {
		if(promotionDetailFragment == null) {
			promotionDetailFragment = new PromotionDetailFragment();
		}
		promotionDetailFragment.updateUI(promotion);
		//
		FragmentManager fragmentManager = getSupportFragmentManager();
		fragmentManager.beginTransaction()
				.replace(R.id.content_frame, promotionDetailFragment)
				.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
				.addToBackStack("PromotionDetailFragment").commit();
	}
	
	private FoodGridViewFragment foodGridViewFragment;
	public void showFoodFragment(String foodTypeID) {
		if(foodGridViewFragment == null) {
			foodGridViewFragment = new FoodGridViewFragment();
		}
		foodGridViewFragment.updateFoodListByFoodTypeID(foodTypeID);
		//
		FragmentManager fragmentManager = getSupportFragmentManager();
		fragmentManager.beginTransaction()
		.replace(R.id.content_frame, foodGridViewFragment)
		.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
		.addToBackStack("FoodGridViewFragment").commit();
	}
	
	private MenuPreOrderFragment menuPreOrderFragment;
	public void showMenuPreOrderFragment() {
		if(menuPreOrderFragment == null) {
			menuPreOrderFragment = new MenuPreOrderFragment();
		}
//		menuPreOrderFragment.updateUI(promotion);
		//
		FragmentManager fragmentManager = getSupportFragmentManager();
		fragmentManager.beginTransaction()
				.replace(R.id.content_frame, menuPreOrderFragment)
				.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
				.addToBackStack("MenuPreOrderFragment").commit();
	}
	
	private YourPreOrderFragment yourPreOrderFragment;
	public void showYourPreOrderFragment() {
		if(!mBtnPreOder.isSelected()) {
			finishAllFragment();
			yourPreOrderFragment = new YourPreOrderFragment();
			//Xu Ly UI
			unSelectedAll();
			mBtnPreOder.setSelected(true);
			mDrawerLayout.closeDrawer(menuLeftDrawer);
			 // update the main content by replacing fragments
	        FragmentManager fragmentManager = getSupportFragmentManager();
	        fragmentManager.beginTransaction().replace(R.id.content_frame, yourPreOrderFragment).commit();
		} else {
			mDrawerLayout.closeDrawer(menuLeftDrawer);
		}
	}
	
	public void showPromotionListViewFragment() {
		if(!mBtnPromotion.isSelected()) {
			finishAllFragment();
			promotionListViewFragment = new PromotionListViewFragment();
			//Xu Ly UI
			unSelectedAll();
			mBtnPromotion.setSelected(true);
			mDrawerLayout.closeDrawer(menuLeftDrawer);
			 // update the main content by replacing fragments
	        FragmentManager fragmentManager = getSupportFragmentManager();
	        fragmentManager.beginTransaction().replace(R.id.content_frame, promotionListViewFragment).commit();
		} else {
			mDrawerLayout.closeDrawer(menuLeftDrawer);
		}
	}
	
	public void showPlacesFragment() {
		if(!mBtnPlaces.isSelected()) {
			finishAllFragment();
			placesFragment = new PlacesFragment();
			//Xu Ly UI
			unSelectedAll();
			mBtnPlaces.setSelected(true);
			mDrawerLayout.closeDrawer(menuLeftDrawer);
			 // update the main content by replacing fragments
	        FragmentManager fragmentManager = getSupportFragmentManager();
	        fragmentManager.beginTransaction().replace(R.id.content_frame, placesFragment).commit();
		} else {
			mDrawerLayout.closeDrawer(menuLeftDrawer);
		}
	}
	
	private void finishAllFragment() {
		while(getSupportFragmentManager().getBackStackEntryCount() > 0) {
			getSupportFragmentManager().popBackStackImmediate();
		}
		if(saleFragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
	        fragmentManager.beginTransaction().remove(saleFragment).commit();
	        saleFragment = null;
		}
		
		if(loginFragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
			fragmentManager.beginTransaction().remove(loginFragment).commit();
			loginFragment = null;
		}
		
		if(aboutUsFragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
			fragmentManager.beginTransaction().remove(aboutUsFragment).commit();
			aboutUsFragment = null;
		}
		
		if(promotionDetailFragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
	        fragmentManager.beginTransaction().remove(promotionDetailFragment).commit();
	        promotionDetailFragment = null;
		}
		
		if(menuGridViewFragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
	        fragmentManager.beginTransaction().remove(menuGridViewFragment).commit();
	        menuGridViewFragment = null;
		}
		
		if(foodGridViewFragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
	        fragmentManager.beginTransaction().remove(foodGridViewFragment).commit();
	        foodGridViewFragment = null;
		}
		
		if(menuPreOrderFragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
	        fragmentManager.beginTransaction().remove(menuPreOrderFragment).commit();
	        menuPreOrderFragment = null;
		}
		
		if(reservationFragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
			fragmentManager.beginTransaction().remove(reservationFragment).commit();
			reservationFragment = null;
		}
		
		if(editReservationFragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
			fragmentManager.beginTransaction().remove(editReservationFragment).commit();
			editReservationFragment = null;
		}
		
		if(reservationAddMoreInfoFragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
			fragmentManager.beginTransaction().remove(reservationAddMoreInfoFragment).commit();
			reservationAddMoreInfoFragment = null;
		}
		
		if(yourPreOrderFragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
	        fragmentManager.beginTransaction().remove(yourPreOrderFragment).commit();
	        yourPreOrderFragment = null;
		}
		
		if(promotionListViewFragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
	        fragmentManager.beginTransaction().remove(promotionListViewFragment).commit();
	        promotionListViewFragment = null;
		}
		
		if(placesFragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
	        fragmentManager.beginTransaction().remove(placesFragment).commit();
	        placesFragment = null;
		}
		//...
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		hideProcessDialog();
		//register in onCreate and unregister in onDestroy
		ManagingNetwork.unRegisterReceiver();
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnMembershipMain:
			showMembershipFragment();
			break;
		case R.id.btnPromotionMain:
			showPromotionListViewFragment();
			break;
		case R.id.btnMenuMain:
			/*
			 * Khi vao FoodGirviewFragment, bam xo ra menu roi chon Menu thi se
			 * reload lai trang menu category
			 */
			if(foodGridViewFragment != null && foodGridViewFragment.isVisible()) {
				mBtnMenu.setSelected(false);
			}
			showMenuFragment();
			break;
		case R.id.btnReservationMain:
			showReservationFragment();
			break;
		case R.id.btnPreOderMain:
			showYourPreOrderFragment();
			break;
		case R.id.btnAboutUsMain:
			showAboutUsFragment();
			break;
		case R.id.btnPlacesMain:
			showPlacesFragment();
			break;
		default:
			break;
		}
	}
}
